package com.example.myapplication

import android.media.MediaPlayer
import android.media.RingtoneManager
import android.os.Bundle
import android.os.CountDownTimer
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.myapplication.ui.theme.MyApplicationTheme
import kotlin.math.abs
import kotlin.math.roundToInt

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MyApplicationTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    CountdownTimerApp(modifier = Modifier.padding(innerPadding))
                }
            }
        }
    }
}

@Composable
fun CountdownTimerApp(modifier: Modifier = Modifier) {
    val context = LocalContext.current
    val view = LocalView.current
    
    // 使用rememberSaveable保存状态
    var sliderPosition by rememberSaveable { mutableFloatStateOf(1f) }
    var isCountingDown by rememberSaveable { mutableStateOf(false) }
    var remainingTimeInSeconds by rememberSaveable { mutableIntStateOf(60) }
    var selectedMinutes by rememberSaveable { mutableIntStateOf(1) }
    var totalTimeInSeconds by rememberSaveable { mutableIntStateOf(60) }
    var isCountdownFinished by rememberSaveable { mutableStateOf(false) }
    var isNegativeTime by rememberSaveable { mutableStateOf(false) }
    var negativeTimeInSeconds by rememberSaveable { mutableIntStateOf(0) }
    
    // 使用remember保存计时器引用，因为计时器对象不能直接保存
    var countDownTimer by remember { mutableStateOf<CountDownTimer?>(null) }
    var negativeTimer by remember { mutableStateOf<CountDownTimer?>(null) }
    
    // 获取系统提示音
    val notificationSound = remember {
        RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
    }
    
    // 控制屏幕常亮
    DisposableEffect(isCountingDown, isNegativeTime) {
        if (isCountingDown || isNegativeTime) {
            view.keepScreenOn = true
        } else {
            view.keepScreenOn = false
        }
        
        onDispose {
            view.keepScreenOn = false
        }
    }
    
    // 格式化时间显示函数
    fun formatTime(totalSeconds: Int, isNegative: Boolean = false): String {
        val absSeconds = abs(totalSeconds)
        val minutes = absSeconds / 60
        val seconds = absSeconds % 60
        return if (isNegative) {
            "-${String.format("%02d:%02d", minutes, seconds)}"
        } else {
            String.format("%02d:%02d", minutes, seconds)
        }
    }
    
    // 当滑杆值变化时更新显示时间
    fun updateSelectedTime(minutes: Int) {
        selectedMinutes = minutes
        remainingTimeInSeconds = minutes * 60
        isCountdownFinished = false
        isNegativeTime = false
        negativeTimeInSeconds = 0
    }
    
    // 开始负时间计时
    fun startNegativeTimer() {
        isNegativeTime = true
        negativeTimer = object : CountDownTimer(Long.MAX_VALUE, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                negativeTimeInSeconds++
            }
            
            override fun onFinish() {
                // 这个方法不会被调用，除非手动取消计时器
            }
        }.start()
    }
    
    // 开始倒计时
    fun startCountdown() {
        // 取消之前的计时器
        countDownTimer?.cancel()
        negativeTimer?.cancel()
        
        isCountingDown = true
        isCountdownFinished = false
        isNegativeTime = false
        negativeTimeInSeconds = 0
        totalTimeInSeconds = remainingTimeInSeconds
        
        // 用于跟踪是否已经播放了声音
        var soundPlayed = false
        
        countDownTimer = object : CountDownTimer(remainingTimeInSeconds * 1000L, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                remainingTimeInSeconds = (millisUntilFinished / 1000).toInt()
                
                // 当剩余1秒时播放提示音
                if (remainingTimeInSeconds == 1 && !soundPlayed) {
                    soundPlayed = true
                    try {
                        val ringtone = RingtoneManager.getRingtone(context, notificationSound)
                        ringtone.play()
                    } catch (e: Exception) {
                        // 处理播放错误
                    }
                }
            }
            
            override fun onFinish() {
                remainingTimeInSeconds = 0
                isCountdownFinished = true
                startNegativeTimer()
            }
        }.start()
    }
    
    // 释放资源
    DisposableEffect(Unit) {
        onDispose {
            countDownTimer?.cancel()
            negativeTimer?.cancel()
        }
    }
    
    // 在Activity重建时，如果正在倒计时，重新启动倒计时
    LaunchedEffect(isCountingDown, isNegativeTime) {
        if (isCountingDown && !isNegativeTime) {
            // 重新启动倒计时
            startCountdown()
        } else if (isNegativeTime) {
            // 重新启动负时间计时
            startNegativeTimer()
        }
    }
    
    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        // 时间显示
        if (isNegativeTime) {
            // 显示负时间
            Text(
                text = formatTime(negativeTimeInSeconds, true),
                fontSize = 72.sp,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center,
                color = Color.Red, // 负时间显示为红色
                modifier = Modifier.padding(bottom = 24.dp)
            )
        } else {
            // 显示正常时间
            Text(
                text = formatTime(remainingTimeInSeconds),
                fontSize = 72.sp,
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center,
                modifier = Modifier.padding(bottom = 24.dp)
            )
        }
        
        // 进度条 - 只在倒计时期间显示且不在负时间模式下
        if (isCountingDown && totalTimeInSeconds > 0 && !isNegativeTime) {
            // 计算进度 - 从1.0倒数到0.0
            val progress = remainingTimeInSeconds.toFloat() / totalTimeInSeconds.toFloat()
            val progressPercent = (progress * 100).toInt()
            
            // 进度百分比显示
            Text(
                text = "剩余时间: $progressPercent%",
                fontSize = 16.sp,
                modifier = Modifier.padding(bottom = 8.dp)
            )
            
            // 使用明确的自定义颜色
            LinearProgressIndicator(
                progress = progress,
                modifier = Modifier
                    .fillMaxWidth(0.8f)
                    .height(30.dp)
                    .padding(bottom = 16.dp),
                color = Color(0xFF2196F3),  // 蓝色
                trackColor = Color(0xFFE0E0E0)  // 浅灰色
            )
        } else if (isNegativeTime) {
            // 负时间模式下显示超时信息
            Text(
                text = "已超时",
                fontSize = 16.sp,
                color = Color.Red,
                modifier = Modifier.padding(bottom = 8.dp)
            )
            
            Spacer(modifier = Modifier.height(46.dp)) // 与进度条等高的空白
        } else {
            // 添加一个空白间距，保持布局一致
            Spacer(modifier = Modifier.height(70.dp))
        }
        
        // 滑杆标题
        if (!isCountingDown && !isNegativeTime) {
            Text(
                text = "设置时间: $selectedMinutes 分钟",
                fontSize = 18.sp,
                modifier = Modifier.padding(bottom = 16.dp)
            )
            
            // 滑杆
            Slider(
                value = sliderPosition,
                onValueChange = { newValue ->
                    sliderPosition = newValue
                    updateSelectedTime((1 + newValue * 29).roundToInt())
                },
                onValueChangeFinished = {
                    // 滑杆释放后自动开始倒计时
                    startCountdown()
                },
                valueRange = 0f..1f,
                steps = 29,
                modifier = Modifier.padding(horizontal = 16.dp)
            )
        } else {
            Button(
                onClick = {
                    countDownTimer?.cancel()
                    negativeTimer?.cancel()
                    isCountingDown = false
                    isNegativeTime = false
                    updateSelectedTime(selectedMinutes)
                },
                modifier = Modifier.padding(top = 16.dp)
            ) {
                Text("重置")
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun CountdownTimerPreview() {
    MyApplicationTheme {
        CountdownTimerApp()
    }
}